import io
import os
import random
import string

from PIL import Image, ImageDraw, ImageFont
from django.http import HttpResponse

from ultimateshop.settings import BASE_DIR




def get_color():
    colornum = random.shuffle([i for i in range(255)])
    color = tuple(random.sample(colornum, 3))
    return color



def getvcode(request):
    str_all = string.digits + string.ascii_letters
    str_f = random.sample(str_all, 4)
    vcode = ''.join(str_f)
    request.session['vcode'] = vcode
    color_image = get_color()
    image = Image.new('RGB', (150,30), color=color_image)

    draw = ImageDraw.Draw(image)

    color_point = get_color()

    for i in range(0,700):
        postion = (random.randint(0, 150), random.randint(0, 50))
        draw.point(postion, fill=color_point)



    path = os.path.join(BASE_DIR, 'static', 'font', 'ARLBD.TTF')

    font = ImageFont.turetype(font=path, size=60)
    font_color = get_color()
    draw.text((20,10), vcode, fill=font_color, font=font)

    buffer = io.BytesIO()
    image.save(buffer, 'png')
    return buffer.getvalue()